import { reactive, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue';
import page from './page.ts';
import { useRouter, useRoute } from 'vue-router';
export function useListComponent(props: any = {}) {
  const router = useRouter();
  const route = useRoute();
  const { proxy } = getCurrentInstance() as any;

  //页面信息
  const options = reactive({
    state: [
      {
        label: '盘点中',
        value: 0,
        type: '',
      },
      {
        label: '已完成',
        value: 1,
        type: 'success',
      },
    ],
    onlyStocked: [
      {
        label: '全部',
        value: -1,
        type: 'info',
      },
      {
        label: '仅显示',
        value: 0,
        type: 'success',
      },
      {
        label: '不显示',
        value: 1,
        type: 'success',
      },
    ],
  });
  //页面信息
  const dataInfo: any = reactive({
    loading: false, //加载
    loadingMsg: '列表数据加载中', //加载
    table: {
      title: page.title, //表格-标题
      //表格-内容数据
      tbody: [],
      rowKey: 'productSpecificationNumber',
      theadCode: 'selectProductStockList', //basedatatable
      //表格-表头数据
      thead: [],
      //表格-搜索数据
      search: {
        pageIndex: 1, //当前页码
        pageSize: 30, //每页显示数据的数量
        totalCount: 0, //总数量
        queryDataBaseFiled: '', // 关键字查询字段，空值查询全部
        likeWords: '', // 查询关键字，空值查询全部
        onlySelf: 0, // 是否只查询自己创建的，0：查所有、1：只查自己创建的
        isShowDisabled: -1, // 是否显示禁用,-1：显示所有的；0：仅显示未作废的；1 仅显示作废的
        orderByFiled: '', // 排序字段
        orderByType: 1, // 排序方式，0-倒序,1-升序
        onlyStocked: 1, // -1：显示全部、0：仅显示0库存、1：不显示0库存
        beginTime: '', // 生产日期范围-开始时间
        endTime: '', // 生产日期范围-结束时间
        //
        productNo: '', //成品编号
      },
      spanMethod: ({ row, column, rowIndex, columnIndex }) => {
        let isColumn = [
          'productNumber', //
          'productName',
          'customerName',
          'productSpecificationNumber',
          'productSpecificationName',
          'printingMaterials',
          'productLayout',
          'productVersion',
          'deliveringQuantity',
          'lastInStockTime',
          'updateTime',
          'productUnit',
          'updatorName',
        ].includes(column.property);
        if (isColumn && row.rowspan >= 0) {
          // const _text = `${column.property}：${row[column.property]},[行：${row.rowIndex},列：${columnIndex},合并：${row.rowspan}]`;
          if (row.rowspan === 0) {
            return {
              rowspan: 0,
              colspan: 0,
            };
          } else {
            return {
              rowspan: row.rowspan,
              colspan: 1,
            };
          }
        }
      },
      //多选
      checkbox: {
        state: true,
        selectable: (row: any) => {
          return true;
        },
        list: [],
      },
      //表格-按钮数据
      btns: [
        {
          title: '导出数据',
          icon: 'Download',
          type: '',
          children: [
            {
              title: '导出当页数据',
              click: () => {
                setLoading('导出当页数据,请稍等');
                exportBtn(dataInfo.table.tbody);
              },
            },
            {
              title: '导出全部数据',
              click: () => {
                setLoading('正在导出全部数据,请稍等');
                proxy.$api.FinishedProduct.GetFinishedProductStockPageList({
                  ...dataInfo.table.search,
                  pageIndex: 1,
                  pageSize: 10000,
                  beginTime: dataInfo.table.search.beginTime || proxy.$getTimeAgo(1, 'years'), // 开始时间
                  endTime: dataInfo.table.search.endTime || proxy.$day(new Date()), // 结束时间
                })
                  .then((res: any) => {
                    exportBtn(res.list);
                  })
                  .catch(() => {
                    dataInfo.loading = false;
                  });
              },
            },
            {
              title: '导出选中数据',
              click: () => {
                setLoading('导出选中数据,请稍等');
                exportBtn(dataInfo.table.checkbox.list);
              },
            },
          ],
        },
      ],
      //表格-列表搜索
      operation: [
        {
          title: (row: any) => {
            return row.isUsed === 0 ? '编辑' : '查看';
          },
          click: (row: any) => {
            lookBtn(row);
          },
        },
      ],
    },
  });
  // 查看
  const lookBtn = (row: any) => {
    proxy.$openPup(props.pup, 3);
    props.pup.form = {
      ...row,
      inventory: [],
      changeLog: [],
    };
    props.pup.loading = true;
    Promise.all([
      getInventory(), //修改产品信息
      getChangeLog(), //修改阶梯价信息
    ])
      .then((res: any) => {
        props.pup.loading = false;
      })
      .catch(() => {});
  };
  //获取库存
  const getInventory = (pup: any = props.pup) => {
    return new Promise((resolve, reject) => {
      proxy.$api.FinishedProduct.GetFinishedProductStockDetailPageList({
        pageIndex: 1, //当前页码
        pageSize: 999, //每页显示数据的数量
        productNo: pup.form.productNo,
        onlyStocked: 1, //仅查看有库存，-1 查全部、0-仅查库存数量为0的、1-仅查库存数量大于0的
      })
        .then((res: any) => {
          pup.form.inventory = res.list.map((el: any) => ({
            ...el,
            rowClass: el.productStockNo === pup.form.productStockNo ? 'primary-row' : '',
          }));
          resolve(res);
        })
        .catch((e: any) => {
          reject(e);
        });
    });
  };
  //获取变化明细
  const getChangeLog = (pup: any = props.pup) => {
    return new Promise((resolve, reject) => {
      proxy.$api.FinishedProduct.GetPageProductStockChangeLogList({
        ...pup.search,
        productNo: pup.form.productNo,
        productStockNo: pup.form.productStockNo,
      })
        .then((res: any) => {
          pup.form.changeLog = res.list.map((el: any) => {
            const _changeQuantity = el.changeType.includes('入库') ? Number(el.changeQuantity) : -Number(el.changeQuantity);
            return {
              ...el,
              productionDate: proxy.$day(el.productionDate),
              changeQuantity: _changeQuantity,
              afterStockQuantity1: proxy.$count(`${el.afterChangeQuantity || 0}-${_changeQuantity || 0}`),
              rowClass: el.productStockNo === pup.form.productStockNo ? 'primary-row' : '',
            };
          });
          pup.search.totalCount = res.totalCount;
          resolve(res);
        })
        .catch((e: any) => {
          reject(e);
        });
    });
  };
  // 获取表数据
  const getTbody = () => {
    let _table: any = dataInfo.table;
    setLoading();
    proxy.$api.FinishedProduct.GetFinishedProductStockPageList(_table.search)
      .then((res: any) => {
        let _list: any = [];
        let rowIndex = 1;
        res.list.forEach((el: any, elIndex: number) => {
          const _chilch = el.details;
          if (_chilch && _chilch.length > 0) {
            _chilch.forEach((chilch: any, chilchIndex: number) => {
              _list.push({
                ...el,
                ...chilch,
                rowIndex: rowIndex,
                rowspan: chilchIndex === 0 ? _chilch.length : 0,
                rowClass: elIndex % 2 ? 'primary-row' : '',
              });
              rowIndex++;
            });
          } else {
            _list.push({
              ...el,
              rowIndex: rowIndex,
              backQuantity: '',
              actualQuantity: '',
              goodsName: '',
              specificationName: '',
              firstQuantity: '',
              secondQuantity: '',
              price: '',
              amount: '',
              totalAmount: '',
              rowspan: 1,
              rowClass: elIndex % 2 ? 'primary-row' : '',
            });
            rowIndex++;
          }
        });
        _table.tbody = _list;
        _table.search.totalCount = res.totalCount;
        dataInfo.loading = false;
      })
      .catch(() => {
        dataInfo.loading = false;
      });
  };
  // 导出数据
  const exportBtn = (tbody: any[]) => {
    proxy.$exportData(
      {
        thead: dataInfo.table.thead,
        tbody: tbody,
        fileName: dataInfo.table.title,
      },
      dataInfo,
    );
    dataInfo.loading = false;
  };
  const setLoading = (title: string = '正在获取数据,请稍等...') => {
    if (!dataInfo.loading) {
      dataInfo.loading = true;
      dataInfo.loadingMsg = title;
    }
  };
  // 组件挂载后执行
  onMounted(() => {
    getTbody();
  });
  // 组件卸载前执行
  onBeforeUnmount(() => {});
  return { dataInfo, getTbody, getChangeLog, options };
}
